package definite.Guide.Book.ToggleButton;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;

import javax.swing.AbstractButton;
import javax.swing.ButtonModel;
import javax.swing.JFrame;
import javax.swing.JToggleButton;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;

public class JToggleHandlingEvent {

	public static void main(String[] args) {

		Runnable run = new Runnable() {

			@Override
			public void run() {

				JFrame frame = new JFrame("Handling JToggle Event");
				frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

				JToggleButton btnToggle = new JToggleButton(new DiamondIcon(
						Color.PINK), true);

				// define action listener
				ActionListener actionListener = new ActionListener() {

					@Override
					public void actionPerformed(ActionEvent e) {
						AbstractButton button = (AbstractButton) e.getSource();
						boolean selected = button.isSelected();
						System.out.println("Action - Selected : " + selected);
					}
				};

				// define change Listener
				ChangeListener changeListener = new ChangeListener() {

					@Override
					public void stateChanged(ChangeEvent e) {
						AbstractButton button = (AbstractButton) e.getSource();
						ButtonModel buttonModel = button.getModel();
						boolean armed = buttonModel.isArmed();
						boolean pressed = buttonModel.isPressed();
						boolean selected = buttonModel.isSelected();
						System.out.println("Changed: " + armed + "/" + pressed
								+ "/" + selected);
					}
				};

				// define Item Listener
				ItemListener itemListener = new ItemListener() {

					@Override
					public void itemStateChanged(ItemEvent e) {
						int state = (int) e.getStateChange();
						if (state == ItemEvent.SELECTED)
							System.out.println("Selected");
						else
							System.out.println("DeSelected");
						System.out.println("\n\n");
					}
				};

				// Attact Listener
				btnToggle.addActionListener(actionListener);
				btnToggle.addChangeListener(changeListener);
				btnToggle.addItemListener(itemListener);

				frame.setLayout(new BorderLayout());
				frame.add(btnToggle, BorderLayout.NORTH);
				frame.setLocationRelativeTo(null);
				frame.setSize(300, 125);
				frame.setVisible(true);
			}
		};

		EventQueue.invokeLater(run);
	}

}
